package com.ruoyi.plasma.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.plasma.domain.PlasmaDonor;
import com.ruoyi.plasma.domain.PlasmaUncollectionStatistics;
import com.ruoyi.plasma.service.IPlasmaUncollectionStatisticsService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tongji.entity.宣传员;
import com.ruoyi.tongji.run.manager.ManagerFactory;
import com.ruoyi.tongji.run.每月员工统计;
import com.ruoyi.tongji.run.每月联络员统计;
import com.ruoyi.tongji.run.车主路费统计直接走系统;
import com.ruoyi.tongji.utils.DateUtil;
import com.ruoyi.tongji.utils.DateUtils;
import org.apache.commons.io.IOUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/plasma")
public class PlasmaController
{
    private static final Logger log = LoggerFactory.getLogger(PlasmaController.class);

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private IPlasmaUncollectionStatisticsService plasmaUncollectionStatisticsService;
    @Autowired
    private ISysUserService userService;

    public static void main(String[] args) {
        String year = "2025";

        SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
        String indicatorSql = "select * from sys_user where user_id > 99";
        List<HashMap> userList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {}), HashMap.class);
        PlasmaController pc = new PlasmaController();

        List<HashMap> list = new ArrayList();
        for (Iterator<HashMap> iterator = userList.iterator(); iterator.hasNext(); ) {
            HashMap<String, String> user =  iterator.next();
            for (int month = 1; month <= 12 ; month++) {
                String day = year + "-" + (month<10?(0+""+month):month) + "-" + "01";
                String userName = user.get("userName");
                AjaxResult result = pc.taskIndicatorsYicilv(null,null,userName,day);
                ((HashMap)result.get("data")).put("月份", month+"月");
                ((HashMap)result.get("data")).put("年份", year);
                list.add((HashMap)result.get("data"));

            }
        }

        for (Iterator<HashMap> iterator = list.iterator(); iterator.hasNext(); ) {
            HashMap data =  iterator.next();
            System.out.print(((HashMap)data.get("task_indicators_statistics")).get("姓名") + "\t");
            System.out.print(data.get("月份") + "\t");
            System.out.print(data.get("年份") + "\t");
            System.out.print(((HashMap)data.get("task_indicators_statistics")).get("当年一次率") + "\t");
            System.out.print(((HashMap)data.get("task_indicators_statistics")).get("当年献浆一次人数") + "\t");
            System.out.print(((HashMap)data.get("task_indicators_statistics")).get("当年献浆总人数") + "\t");
            System.out.println();
        }


    }
    //@PreAuthorize("@ss.hasPermi('plasma:statistics:day:detail')")
    //查看任务指标
    @GetMapping("/view/task/indicators_remark")
    public AjaxResult taskIndicatorsRemark(HttpServletResponse response, HttpServletRequest request)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        HashMap data = new HashMap();

        SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
        SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();

        String userName = user.getUserName();
        String remark = user.getRemark();
        Long userId = user.getUserId();
        String month = DateUtil.getMonth(new Date()) + "月";
        String year = DateUtil.getYear(new Date()) + "年";

        int jidu = DateUtil.getJidu(new Date());

        String indicatorSql = "select *," +
                "(select sum(tongqi_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度检疫期数量," +
                "(select sum(tongqi_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度超半年数量," +
                "(select sum(now_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度检疫期数量," +
                "(select sum(now_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度超半年数量" +
                " from plasma_user_indicators where user_id = ? and month = ? and year = ?";
        List<HashMap> indicatorSqlResultList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {userId, jidu, userId, jidu, userId, jidu, userId, jidu, userId, month, year}), HashMap.class);
        if (indicatorSqlResultList.size() > 0) data.put("task_indicators",indicatorSqlResultList.get(0));

        String year_start_date = DateUtil.getYearFirstDay(new Date(),"yyyyMMdd");
        String year_end_date = DateUtil.getYearLastDay(new Date(),"yyyyMMdd");
        String year_start_time = year_start_date + "0000000";
        String year_end_time = year_end_date + "2300000";

        String month_start_date = DateUtil.getMonthFirstDay(new Date(),"yyyyMMdd");
        String month_end_date = DateUtil.getMonthLastDay(new Date(),"yyyyMMdd");
        String month_start_time = month_start_date + "0000000";
        String month_end_time = month_end_date + "2300000";

        String jidu_start_date = DateUtil.getJiduFirstDay(new Date(),"yyyyMMdd");
        String jidu_end_date = DateUtil.getJiduLastDay(new Date(),"yyyyMMdd");

        String pre_year_start_date = DateUtil.getLastYearFirstDay(new Date(), "yyyyMMdd");
        String pre_year_end_date = DateUtil.getLastYearLastDay(new Date(), "yyyyMMdd");

        List<HashMap> resultList = taibangSqlManager.execute(new SQLReady(
                "select *,当年献浆总袋数/当年献浆总人数 as 频次, 当年新浆员献浆一次人数/当年新浆员数 as 当年新浆员一次率, 当年献浆一次人数/当年献浆总人数 as 当年一次率, (当年献浆总人数-当年新浆员数)/上年献浆总人数 as 留存率,'' as '^^^^',\n" +
                        "当年浆站献浆总袋数/当年浆站献浆总人数 as 当年浆站频次, 当年浆站新浆员献浆一次人数/当年浆站新浆员数 as 当年浆站新浆员一次率, 当年浆站献浆一次人数/当年浆站献浆总人数 as 浆站一次率, (当年浆站献浆总人数-当年浆站新浆员数)/浆站上年献浆总人数 as 浆站留存率\n" +
                        "\n" +
                        "from (\n" +
                        "select ? as 备注,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ?) as 当年献浆总袋数,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ?) as 当月献浆总袋数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 当年献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 当月献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and d.issuingDate between ? and ? and d.firstCollectDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年新浆员献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 上年献浆总人数,\n" +
                        "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? and (d.remark like CONCAT('%',?,'%'))) as 当年新浆员数,\n" +
                        "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? and (d.remark like CONCAT('%',?,'%'))) as 当月新浆员数,\n" +
                        "'' as '^^^^',\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ?) as 当年浆站献浆总袋数,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ?) as 当月浆站献浆总袋数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 当年浆站献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 当月浆站献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年浆站献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ? and d.issuingDate between ? and ? and d.firstCollectDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年浆站新浆员献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 浆站上年献浆总人数,\n" +
                        "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? ) as 当年浆站新浆员数,\n" +
                        "'' as '召回'," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId where d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本年召回数量," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId where d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本月召回数量," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId where d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本季度召回数量" +
                        ") as a",
                new Object[] {remark,
                        remark,year_start_date, year_end_date,
                        remark,month_start_date, month_end_date,
                        remark,year_start_date, year_end_date,
                        remark,month_start_date, month_end_date,
                        remark,year_start_date, year_end_date,
                        remark,year_start_date, year_end_date,year_start_time, year_end_time,year_start_time, year_end_time,
                        remark,pre_year_start_date, pre_year_end_date,
                        year_start_time, year_end_time, year_start_time, year_end_time,remark,
                        month_start_time, month_end_time, month_start_time, month_end_time,remark,

                        year_start_date, year_end_date,
                        month_start_date, month_end_date,
                        year_start_date, year_end_date,
                        month_start_date, month_end_date,
                        year_start_date, year_end_date,
                        year_start_date, year_end_date, year_start_time, year_end_time, year_start_time, year_end_time,
                        pre_year_start_date, pre_year_end_date,
                        year_start_time, year_end_time, year_start_time, year_end_time,

                        remark, year_start_date, year_end_date,91,
                        remark, month_start_date, month_end_date,91,
                        remark, jidu_start_date, jidu_end_date,91
                }), HashMap.class);
        if (resultList.size() > 0) data.put("task_indicators_statistics",resultList.get(0));
        return AjaxResult.success(data);
    }

    @GetMapping("/view/task/indicators_xuanchuanyuan")
    public AjaxResult taskIndicatorsXuanchuanyuan(HttpServletResponse response, HttpServletRequest request, @RequestParam(name="userName",defaultValue = "default") String userName, @RequestParam(name="day", defaultValue = "default") String day)
    {
        SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
        SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();
        SysUser user = null;
        if (StringUtils.equals(userName,"default") == false) {
            String indicatorSql = "select * from sys_user where user_name = ?";
            List<HashMap> userList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {userName}), HashMap.class);
            userName = (String)userList.get(0).get("userName");
            String remark = (String)userList.get(0).get("remark");
            user = new SysUser();
            user.setUserName(userName);user.setRemark(remark);
        } else {
            user = SecurityUtils.getLoginUser().getUser();
            userName = user.getUserName();
        }
        if (user == null) {
            return AjaxResult.error("未查询到当前用户");
        }

        Date today = new Date();
        if (StringUtils.equals(day,"default") == false) {
            today = DateUtil.getDate(day,"yyyy-MM-dd");
        }

        HashMap data = new HashMap();


        String remark = user.getRemark();
        Long userId = user.getUserId();
        String month = DateUtil.getMonth(today) + "月";
        String year = DateUtil.getYear(today) + "年";

        int jidu = DateUtil.getJidu(today);

        String indicatorSql = "select *," +
                "(select sum(tongqi_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度检疫期数量," +
                "(select sum(tongqi_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度超半年数量," +
                "(select sum(now_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度检疫期数量," +
                "(select sum(now_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度超半年数量" +
                " from plasma_user_indicators where user_id = ? and month = ? and year = ?";
        List<HashMap> indicatorSqlResultList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {userId, jidu, userId, jidu, userId, jidu, userId, jidu, userId, month, year}), HashMap.class);
        if (indicatorSqlResultList.size() > 0) data.put("task_indicators",indicatorSqlResultList.get(0));

        String year_start_date = DateUtil.getYearFirstDay(today,"yyyyMMdd");
        String year_end_date = DateUtil.getYearLastDay(today,"yyyyMMdd");
        String year_start_time = year_start_date + "0000000";
        String year_end_time = year_end_date + "2300000";

        String month_start_date = DateUtil.getMonthFirstDay(today,"yyyyMMdd");
        String month_end_date = DateUtil.getMonthLastDay(today,"yyyyMMdd");
        String month_start_time = month_start_date + "0000000";
        String month_end_time = month_end_date + "2300000";

        String jidu_start_date = DateUtil.getJiduFirstDay(today,"yyyyMMdd");
        String jidu_end_date = DateUtil.getJiduLastDay(today,"yyyyMMdd");

        String pre_year_start_date = DateUtil.getLastYearFirstDay(today, "yyyyMMdd");
        String pre_year_end_date = DateUtil.getLastYearLastDay(today, "yyyyMMdd");

        List<HashMap> resultList = taibangSqlManager.execute(new SQLReady(
                "select *,当年献浆总袋数/当年献浆总人数 as 频次, 当年新浆员献浆一次人数/当年新浆员数 as 当年新浆员一次率, 当年献浆一次人数/当年献浆总人数 as 当年一次率, (当年献浆总人数-当年新浆员数)/上年献浆总人数 as 留存率,'' as '^^^^',\n" +
                        "当年浆站献浆总袋数/当年浆站献浆总人数 as 当年浆站频次, 当年浆站新浆员献浆一次人数/当年浆站新浆员数 as 当年浆站新浆员一次率, 当年浆站献浆一次人数/当年浆站献浆总人数 as 浆站一次率, (当年浆站献浆总人数-当年浆站新浆员数)/浆站上年献浆总人数 as 浆站留存率\n" +
                        "\n" +
                        "from (\n" +
                        "select ? as 备注, ? as 姓名,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ?) as 当年献浆总袋数,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and l.linkmanName like CONCAT('%',?,'%') and f.recordDate between ? and ?) as 当月献浆总袋数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 当年献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and l.linkmanName like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 当月献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and d.issuingDate between ? and ? and d.firstCollectDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年新浆员献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 上年献浆总人数,\n" +
                        "(select count(*) from t_bims_donor as d left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId  where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? and (d.remark like CONCAT('%',?,'%'))) as 当年新浆员数,\n" +
                        "(select count(*) from t_bims_donor as d left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId  where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? and (l.linkmanName like CONCAT('%',?,'%'))) as 当月新浆员数,\n" +
                        "'' as '^^^^',\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ?) as 当年浆站献浆总袋数,\n" +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ?) as 当月浆站献浆总袋数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 当年浆站献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 当月浆站献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年浆站献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ? and d.issuingDate between ? and ? and d.firstCollectDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年浆站新浆员献浆一次人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and f.recordDate between ? and ? group by d.donorId) as a) as 浆站上年献浆总人数,\n" +
                        "(select count(*) from t_bims_donor as d left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId  where d.issuingDate between ? and ? and d.firstCollectDate between ? and ? ) as 当年浆站新浆员数,\n" +
                        "'' as '召回'," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本年召回数量," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where l.linkmanName like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本月召回数量," +
                        "(select count(*) from t_bims_donor_collect_flow f left join t_bims_plasma_collection c on f.donateNo = c.donateNo left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where l.linkmanName like CONCAT('%',?,'%') and f.recordDate between ? and ? and f.plasmaCollection = 'Y' and c.previousCollectDays >= ? ) as 本季度召回数量" +
                        ") as a",
                new Object[] {
                        remark,userName,
                        remark,year_start_date, month_end_date,//当年献浆总袋数
                        userName,month_start_date, month_end_date,//当月献浆总袋数
                        remark,year_start_date, month_end_date,//当年献浆总人数
                        userName,month_start_date, month_end_date,//当月献浆总人数
                        remark,year_start_date, month_end_date,//当年献浆一次人数
                        remark,year_start_date, month_end_date,year_start_time, month_end_time,year_start_time, month_end_time,//当年新浆员献浆一次人数
                        remark,pre_year_start_date, pre_year_end_date,//浆站上年献浆总人数
                        year_start_time, month_end_time, year_start_time, month_end_time,remark,//当年新浆员
                        month_start_time, month_end_time, month_start_time, month_end_time,userName,//当月新浆员数

                        year_start_date, month_end_date,//当年浆站献浆总袋数
                        month_start_date, month_end_date,//当月浆站献浆总袋数
                        year_start_date, month_end_date,//当年浆站献浆总人数
                        month_start_date, month_end_date,//当月浆站献浆总人数
                        year_start_date, month_end_date,//当年浆站献浆一次人数
                        year_start_date, month_end_date, year_start_time, month_end_time, year_start_time, month_end_time,//当年浆站新浆员献浆一次人数
                        pre_year_start_date, pre_year_end_date,//浆站上年献浆总人数
                        year_start_time, month_end_time, year_start_time, month_end_time,//当年浆站新浆员数

                        remark, year_start_date, year_end_date,91,
                        userName, month_start_date, month_end_date,91,
                        userName, jidu_start_date, jidu_end_date,91
                }), HashMap.class);
        if (resultList.size() > 0) data.put("task_indicators_statistics",resultList.get(0));
        return AjaxResult.success(data);
    }

    public AjaxResult taskIndicatorsYicilv(HttpServletResponse response, HttpServletRequest request, @RequestParam(name="userName",defaultValue = "default") String userName, @RequestParam(name="day", defaultValue = "default") String day)
    {
        SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
        SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();
        SysUser user = null;
        if (StringUtils.equals(userName,"default") == false) {
            String indicatorSql = "select * from sys_user where user_name = ?";
            List<HashMap> userList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {userName}), HashMap.class);
            userName = (String)userList.get(0).get("userName");
            String remark = (String)userList.get(0).get("remark");
            user = new SysUser();
            user.setUserName(userName);user.setRemark(remark);
        } else {
            user = SecurityUtils.getLoginUser().getUser();
            userName = user.getUserName();
        }
        if (user == null) {
            return AjaxResult.error("未查询到当前用户");
        }

        Date today = new Date();
        if (StringUtils.equals(day,"default") == false) {
            today = DateUtil.getDate(day,"yyyy-MM-dd");
        }

        HashMap data = new HashMap();


        String remark = user.getRemark();
        Long userId = user.getUserId();
        String month = DateUtil.getMonth(today) + "月";
        String year = DateUtil.getYear(today) + "年";

        int jidu = DateUtil.getJidu(today);

        String indicatorSql = "select *," +
                "(select sum(tongqi_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度检疫期数量," +
                "(select sum(tongqi_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 同期季度超半年数量," +
                "(select sum(now_count_jianyiqi) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度检疫期数量," +
                "(select sum(now_count_chaobannian) from plasma_user_indicators i where user_id = ? and jidu = ?) as 当年季度超半年数量" +
                " from plasma_user_indicators where user_id = ? and month = ? and year = ?";
        List<HashMap> indicatorSqlResultList =jiangzhanSqlManager.execute(new SQLReady(indicatorSql, new Object[] {userId, jidu, userId, jidu, userId, jidu, userId, jidu, userId, month, year}), HashMap.class);
        if (indicatorSqlResultList.size() > 0) data.put("task_indicators",indicatorSqlResultList.get(0));

        String year_start_date = DateUtil.getYearFirstDay(today,"yyyyMMdd");
        String year_end_date = DateUtil.getYearLastDay(today,"yyyyMMdd");
        String year_start_time = year_start_date + "0000000";
        String year_end_time = year_end_date + "2300000";

        String month_start_date = DateUtil.getMonthFirstDay(today,"yyyyMMdd");
        String month_end_date = DateUtil.getMonthLastDay(today,"yyyyMMdd");
        String month_start_time = month_start_date + "0000000";
        String month_end_time = month_end_date + "2300000";

        String jidu_start_date = DateUtil.getJiduFirstDay(today,"yyyyMMdd");
        String jidu_end_date = DateUtil.getJiduLastDay(today,"yyyyMMdd");

        String pre_year_start_date = DateUtil.getLastYearFirstDay(today, "yyyyMMdd");
        String pre_year_end_date = DateUtil.getLastYearLastDay(today, "yyyyMMdd");

        List<HashMap> resultList = taibangSqlManager.execute(new SQLReady(
                "select *,当年献浆一次人数/当年献浆总人数 as 当年一次率 " +
                        "from (\n" +
                        "select ? as 备注, ? as 姓名,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId) as a) as 当年献浆总人数,\n" +
                        "(select count(*) from (select count(*) from t_bims_donor_collect_flow f left join t_bims_donor d on f.donorId = d.donorId left join t_bims_linkman_donor ld on (d.donorId = ld.donorId and ld.flag = 'Y' and ld.relationType = 'conduct') left join t_bims_linkman l on ld.linkmanId = l.linkmanId   where f.plasmaCollection = 'Y' and d.remark like CONCAT('%',?,'%') and f.recordDate between ? and ? group by d.donorId having count(*) = 1) as a) as 当年献浆一次人数,\n" +
                        "'' as '^^^^'\n" +
                        ") as a",
                new Object[] {
                        remark,userName,
                        remark,year_start_date, month_end_date,//当年献浆总人数
                        remark,year_start_date, month_end_date,//当年献浆一次人数

                }), HashMap.class);
        if (resultList.size() > 0) data.put("task_indicators_statistics",resultList.get(0));
        return AjaxResult.success(data);
    }

    @PreAuthorize("@ss.hasPermi('plasma:statistics:day:detail')")
    @GetMapping("/view/dayReport/detail")
    public AjaxResult dayReportDetail(HttpServletResponse response, HttpServletRequest request)
    {
        HashMap data = new HashMap();
        String dateStart = DateUtil.format(new Date(), "yyyyMMdd");
        String dateEnd = DateUtil.format(new Date(), "yyyyMMdd");

        Calendar twoWeekAgo = Calendar.getInstance();
        twoWeekAgo.setTime(new Date());//设置起时间
        twoWeekAgo.add(Calendar.DATE, -14);//增加一天

        String twoWeekAgoStart = DateUtil.format(twoWeekAgo.getTime(), "yyyyMMdd");
        String twoWeekAgoEnd = DateUtil.format(twoWeekAgo.getTime(), "yyyyMMdd");

        String riqi = DateUtil.format(new Date(),"yyyy-MM-dd");
        Date 日期 = DateUtil.getDate(riqi);

        SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();
        String unCollectionSql = "select ROUND(TIMESTAMPDIFF(MINUTE, 登记时间, 当前时间)/60,1) AS interval_time,a.* from (" +
                "select DATE_FORMAT(r.registerDate,'%Y%m%d%H%i%s') as 登记时间, NOW() as 当前时间," +
                "d.codeDonorState,d.cancelReason,d.phone,f.* " +
                "from t_bims_donor_collect_flow f " +
                "left join t_bims_donor_register r on f.donateNo = r.donateNo  " +
                "left join t_bims_donor d on f.donorId = d.donorId " +
                "where " +
                "f.recordDate between ? and ? and f.plasmaCollection != 'Y' order by r.registerDate asc,d.codeDonorState desc, f.physicalYear asc, f.physicalEcg asc, f.bloodTest asc,f.bloodSampleCollect asc, f.hbBloodTest asc, f.physicalAsk asc, f.physical asc) as a";
        List<HashMap> unCollectionList = taibangSqlManager.execute(new SQLReady(unCollectionSql, new Object[] {dateStart, dateEnd}), HashMap.class);
        for (Iterator<HashMap> iterator = unCollectionList.iterator(); iterator.hasNext(); ) {
            HashMap hashMap =  iterator.next();
            PlasmaUncollectionStatistics pu = new PlasmaUncollectionStatistics();

            //根据日期和流水号定位这个浆员是否已经保存过未采信息
            pu.set日期(日期);
            pu.setProcessNo((Integer)hashMap.get("processno"));
            if (StringUtils.equals((String)hashMap.get("plasmacollection"),"I")){
                pu.setType("3");//脂浆的字典值是3
                hashMap.put("type","3");
                hashMap.put("reason","脂浆");
            }
            List<PlasmaUncollectionStatistics> l = this.plasmaUncollectionStatisticsService.selectPlasmaUncollectionStatisticsList(pu);
            if (l.size() != 0) {
                pu = l.get(0);
                //如果保存过未采信息，把保存的未采信息放到从朗程数据库中取来的数据中，因为朗程只能读取
                hashMap.put("type",pu.getType());
                hashMap.put("reason",pu.getReason());
            }
        }
        /*
        List<HashMap> resultList = new ArrayList<>();
        HashMap map = new HashMap();
        map.put("codeDonorState","N");
        map.put("cancelReason","");
        map.put("donorName","孟凡强");
        map.put("donorNo","3701006272");
        map.put("processNo","9");
        map.put("changeless","N");//N：非固定，Y：固定浆员，NEW：新浆员
        map.put("phone","15264133663");
        map.put("plasmaCollection","I");//脂血
        map.put("plasmaVerify","O");
        map.put("physicalAsk","Y");
        map.put("physical","N");
        map.put("physicalYear","O");
        map.put("physicalEcg","O");
        map.put("bloodTest","O");
        map.put("bloodSampleCollect","O");
        map.put("releaseOrder","N");
        map.put("hbBloodTest","N");
        map.put("plasmaCheck","N");
        map.put("immunity","O");
        map.put("payment","O");
        map.put("physicalPatter","O");
        map.put("retentionSample","O");
        resultList.add(map);

        HashMap map1 = new HashMap();
        map1.put("codeDonorState","YJ");//浆员状态：YJ永拒/ZJ暂拒
        map1.put("cancelReason","询问不合格（支气管哮喘）");//拒绝原因
        map1.put("donorName","党正泽");//浆员姓名
        map1.put("donorNo","3701071928");//浆员编号
        map1.put("processNo","1016");//当日流水号
        map1.put("changeless","NEW");//N：非固定，Y：固定浆员，NEW：新浆员
        map1.put("phone","15264133664");
        map1.put("plasmaCollection","I");//I:脂血；N：未采浆
        map1.put("plasmaVerify","O");//Y/O/N这个属性只有新浆员会有N，其他不管采不采浆都是O
        map1.put("physicalAsk","Y");//Y/O/N，健康征询
        map1.put("physical","N");//Y/O/N，体格检查
        map1.put("physicalYear","O");//Y/O/N胸片录入
        map1.put("physicalEcg","O");//Y/O/N心电图
        map1.put("bloodTest","O");//Y/O/N血液检测
        map1.put("bloodSampleCollect","Y");//Y/O/N标本采集 Y已采集 N未通过 O不用此流程
        map1.put("releaseOrder","N");
        map1.put("hbBloodTest","N");//血红蛋白 N未检测Y已检测I不合格
        map1.put("plasmaCheck","N");//采前核查
        map1.put("immunity","O");//免疫
        map1.put("payment","O");//付款
        map1.put("physicalPatter","O");
        map1.put("retentionSample","O");
        resultList.add(map1);

*/
        data.put("resultList",unCollectionList);//用于存放当日未采人员列表
        String dayDataSql = "select \n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? order by f.processNo) as 登记人数,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.changeless = 'NEW' order by f.processNo) as 新浆员数量,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.changeless = 'N' order by f.processNo) as 非固定浆员数量,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.changeless = 'Y' order by f.processNo) as 固定浆员数量,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.plasmaCollection = 'Y' order by f.processNo) as 采浆量,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.plasmaCollection = 'Y' order by f.processNo) as 上轮采浆量,\n" +
                "(\n" +
                "select count(*) from t_bims_donor_collect_flow f left join t_bims_donor_register r on f.donateNo = r.donateNo where left(f.recordDate,8) between ? and ? and f.plasmaCollection in ('N','I') order by f.processNo) as 未采浆数量";
        List<HashMap> dayDataList = taibangSqlManager.execute(new SQLReady(dayDataSql, new Object[] {dateStart, dateEnd,dateStart, dateEnd,dateStart, dateEnd,dateStart, dateEnd,dateStart, dateEnd,twoWeekAgoStart, twoWeekAgoEnd, dateStart, dateEnd}), HashMap.class);

        data.put("dayData",dayDataList.get(0));

        data.put("date", DateUtil.format(new Date(),"yyyy年MM月dd日"));
        return AjaxResult.success(data);
    }

    /**
     * 日报
     * 
     */
    @PreAuthorize("@ss.hasPermi('plasma:statistics:day')")
    @GetMapping("/view/dayReport")
    public AjaxResult dayReport(HttpServletResponse response, HttpServletRequest request)
    {

        LocalDate currentDate = LocalDate.now();
        String reportKey = currentDate + "-dayReportList";
        request.getSession().getServletContext().removeAttribute(reportKey);
        HashMap data = (HashMap)request.getSession().getServletContext().getAttribute(reportKey);
        if (data == null) {

            data = new HashMap();
            SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
            SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();

            String sql = "select *, (当年献浆总人数-当年发展新浆员数)/上年参与献浆总人数 as 留存率,当年献浆袋数/当年献浆总人数 as 总频次,新浆员采浆袋数/当年发展新浆员数 as 新浆员一针率 from (\n" +
                    "            select\n" +
                    "                    (select count(*) from t_bims_plasma_collection as c where c.beginDate between '202501010000000' and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000') and c.weight > 0) as 当年献浆袋数,\n" +
                    "        (select count(*) from (select count(*) from t_bims_plasma_collection as c where c.beginDate between '202501010000000' and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000') and c.weight > 0 group by c.donorId ) as a) as 当年献浆总人数,\n" +
                    "        (select count(*) from t_bims_donor as d where d.issuingDate between '202501010000000' and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000') and d.firstCollectDate between '202501010000000' and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')) as 当年发展新浆员数,\n" +
                    "        (select count(*) from (select count(*) from t_bims_plasma_collection as c where c.beginDate between '202301010000000' and '202312312300000' and c.weight > 0 group by c.donorId ) as a) as 上年参与献浆总人数,\n" +
                    "        (select count(*) from t_bims_plasma_collection as c left join t_bims_donor as d on c.donorId = d.donorId where d.firstCollectDate between '202501010000000' and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')) as 新浆员采浆袋数\n" +
                    ") as b";
            List<HashMap> resultList = taibangSqlManager.execute(new SQLReady(sql, new Object[] {}), HashMap.class);
            data = resultList.get(0);

            String daySql = "\n" +
                    "select \n" +
                    "DATE_FORMAT(NOW(), '%Y-%m') as 月份, \n" +
                    "(select count(*) from t_bims_plasma_collection as c left join t_bims_donor as d on c.donorId = d.donorId where c.beginDate between DATE_FORMAT(DATE_SUB(STR_TO_DATE(CONCAT(DATE_FORMAT(NOW(), '%Y-%m'), '-01'), '%Y-%m-%d'), INTERVAL 0 DAY),'%Y%m%d0000000') and DATE_FORMAT(LAST_DAY(CURRENT_DATE),'%Y%m%d2300000') and \tc.weight > 0)  as 本月采浆量,\n" +
                    "(select count(*) from t_bims_plasma_collection as c left join t_bims_donor as d on c.donorId = d.donorId where c.beginDate between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000') and \tc.weight > 0)  as 当日采浆量,\n" +
                    "(select count(*) from t_bims_donor as d where d.issuingDate between DATE_FORMAT(DATE_SUB(STR_TO_DATE(CONCAT(DATE_FORMAT(NOW(), '%Y-%m'), '-01'), '%Y-%m-%d'), INTERVAL 0 DAY),'%Y%m%d0000000') and DATE_FORMAT(LAST_DAY(CURRENT_DATE),'%Y%m%d2300000') and d.firstCollectDate between DATE_FORMAT(DATE_SUB(STR_TO_DATE(CONCAT(DATE_FORMAT(NOW(), '%Y-%m'), '-01'), '%Y-%m-%d'), INTERVAL 0 DAY),'%Y%m%d0000000') and DATE_FORMAT(LAST_DAY(CURRENT_DATE),'%Y%m%d2300000')) as 本月建档并献浆数,\n" +
                    "CURRENT_DATE as 当天日期,\n" +
                    "(select count(*) from t_bims_donor as d where d.firstCollectDate between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')) as 当日首次采浆数,\n" +
                    "(select count(*) from t_bims_donor as d where d.issuingDate between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')) as 当日建档数,\n" +
                    "(select count(*) from t_bims_donor as d where d.issuingDate between DATE_FORMAT(DATE_SUB(STR_TO_DATE(CONCAT(DATE_FORMAT(NOW(), '%Y-%m'), '-01'), '%Y-%m-%d'), INTERVAL 0 DAY),'%Y%m%d0000000') and DATE_FORMAT(LAST_DAY(CURRENT_DATE),'%Y%m%d2300000') and d.firstCollectDate between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')) as 本月建档当日献浆数\n" +
                    "\n" +
                    "\n";
            List<HashMap> daySqlResultList = taibangSqlManager.execute(new SQLReady(daySql, new Object[] {}), HashMap.class);
            data.put("dayData",daySqlResultList.get(0));

            LocalDate monthFirstDate = LocalDate.now().withDayOfMonth(1);
            LocalDate monthFixFirstDate = monthFirstDate;
            LocalDate monthLastDate = LocalDate.now().plusDays(1);

            YearMonth yearMonth = YearMonth.of(monthFirstDate.getYear(),monthFirstDate.getMonth());

            String month = yearMonth.getMonth().getValue() + "月";

            String 采浆量Sql = "select indicators from plasma_task_indicators where month = ? and taskName = ?";
            List<HashMap> 采浆量ResultList =jiangzhanSqlManager.execute(new SQLReady(采浆量Sql, new Object[] {month,"采浆量"}), HashMap.class);
            data.put("采浆量",采浆量ResultList.get(0).get("indicators"));

            String 新浆员发展数Sql = "select indicators from plasma_task_indicators where month = ? and taskName = ?";
            List<HashMap> 新浆员发展数ResultList =jiangzhanSqlManager.execute(new SQLReady(新浆员发展数Sql, new Object[] {month,"新浆员发展数"}), HashMap.class);
            data.put("新浆员发展数",新浆员发展数ResultList.get(0).get("indicators"));

            String 留存率Sql = "select indicators from plasma_task_indicators where month = ? and taskName = ?";
            List<HashMap> 留存率ResultList =jiangzhanSqlManager.execute(new SQLReady(留存率Sql, new Object[] {month,"目标留存率"}), HashMap.class);
            data.put("目标留存率",留存率ResultList.get(0).get("indicators"));

            String 目标频次Sql = "select indicators from plasma_task_indicators where month = ? and taskName = ?";
            List<HashMap> 目标频次ResultList =jiangzhanSqlManager.execute(new SQLReady(目标频次Sql, new Object[] {month,"目标频次"}), HashMap.class);
            data.put("目标频次",目标频次ResultList.get(0).get("indicators"));

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); // 设置日期格式为"年-月-日"
            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); // 设置日期格式为"年-月-日"

            data.put("date", DateUtil.format(new Date(),"yyyy年MM月dd日"));
            List dayReportList = new ArrayList();


            int shengyuMonthDays = yearMonth.lengthOfMonth() - DateUtil.getMondayCount(null);

            data.put("shengyuMonthDays",shengyuMonthDays);

            while (monthFirstDate.isBefore(monthLastDate)) {

                LocalDate date = monthFirstDate;
                DayOfWeek dayOfWeek = date.getDayOfWeek();
                monthFirstDate = monthFirstDate.plusDays(1);
                if (com.ruoyi.common.utils.StringUtils.equals(dayOfWeek.name(),"MONDAY")) {
                    continue;
                }

                shengyuMonthDays = shengyuMonthDays - 1;
                String dayReportKey = date + "-dayReport";
                HashMap result = (HashMap)request.getSession().getServletContext().getAttribute(dayReportKey);

                if (date.getDayOfYear() == LocalDate.now().getDayOfYear()) {//当天数据查一下，不是当天的放到缓存里
                    result = null;
                }
                if (result == null) {
                    result = new HashMap();
                    String monthFirstDateString = monthFixFirstDate.format(formatter) + "0000000";
                    String monthCurrentDateStartString = date.format(formatter) + "0000000";
                    String monthCurrentDateEndString = date.format(formatter) + "2300000";

                    String dayReportSql = "\n" +
                            "select \n" +
                            "DATE_FORMAT(NOW(), '%Y-%m') as 月份, \n" +
                            "(select count(*) from t_bims_plasma_collection as c left join t_bims_donor as d on c.donorId = d.donorId where c.beginDate between ? and ? and \tc.weight > 0)  as 本月采浆量,\n" +
                            "(select count(*) from t_bims_plasma_collection as c left join t_bims_donor as d on c.donorId = d.donorId where c.beginDate between ? and ? and \tc.weight > 0)  as 当日采浆量,\n" +
                            "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ? and d.firstCollectDate between ? and ?) as 本月建档并献浆数,\n" +
                            "'" + date.format(formatter1)+ "' as 当天日期,\n" +
                            "(select count(*) from t_bims_donor as d where d.firstCollectDate between ? and ?) as 当日首次采浆数,\n" +
                            "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ?) as 当日建档数,\n" +
                            "(select count(*) from t_bims_donor as d where d.issuingDate between ? and ? and d.firstCollectDate between ? and ?) as 本月建档当日献浆数\n" +
                            "\n" +
                            "\n";
                    List<HashMap> dayReportSqlList = taibangSqlManager.execute(new SQLReady(dayReportSql, new Object[] {monthFirstDateString,monthCurrentDateEndString,monthCurrentDateStartString,monthCurrentDateEndString,monthFirstDateString,monthCurrentDateEndString,monthFirstDateString,monthCurrentDateEndString,monthCurrentDateStartString,monthCurrentDateEndString,monthCurrentDateStartString,monthCurrentDateEndString,monthFirstDateString,monthCurrentDateEndString,monthCurrentDateStartString,monthCurrentDateEndString}), HashMap.class);

                    result = dayReportSqlList.get(0);

                    result.put("剩余天数",shengyuMonthDays);
                    request.getSession().getServletContext().setAttribute(dayReportKey, result);

                }
                dayReportList.add(result);
            }
            data.put("dayReportList",dayReportList);

            request.getSession().getServletContext().setAttribute(reportKey, data);
        }
        return AjaxResult.success(data);
    }

    /**
     * 判断浆员是否挂号
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/view/isRegister/{donorNo}")
    public AjaxResult isRegister(@PathVariable String donorNo, HttpServletResponse response, HttpServletRequest request)
    {
        boolean isRegister = this.isRegister(donorNo);

        if (isRegister == true) {
            SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
            String selectPublicMealTicketSql = "select * from plasma_meal_ticket as m where (m.donorNo = ? or m.processNo = ?) and m.publicTime between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')";
            List<HashMap> publicMealTicketList = jiangzhanSqlManager.execute(new SQLReady(selectPublicMealTicketSql, new Object[] {donorNo,donorNo}), HashMap.class);
            if (publicMealTicketList.size()> 0) {
                HashMap publicMealTicket = publicMealTicketList.get(0);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssS");
                return AjaxResult.error("餐券已发放，不能重复发放，发放时间：" + publicMealTicket.get("publictime"));
            }
            return AjaxResult.success("该浆员已挂号，未领券，可以领券。");
        } else {
            return AjaxResult.error("该浆员未挂号");
        }
    }

    /**
     * 获取发放数量，当天
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/view/publicMealTicketCount")
    public AjaxResult publicMealTicketCount(HttpServletResponse response, HttpServletRequest request)
    {
        SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
        String selectPublicMealTicketSql = "select count(*) as count from plasma_meal_ticket as m where m.publicTime between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')";
        List<HashMap> publicMealTicketList = jiangzhanSqlManager.execute(new SQLReady(selectPublicMealTicketSql, new Object[] {}), HashMap.class);
        if (publicMealTicketList.size()> 0) {
            HashMap mealTicket = publicMealTicketList.get(0);
            return AjaxResult.success(mealTicket.get("count").toString());
        } else {
            return AjaxResult.error();
        }
    }

    public boolean isRegister(String donorNo) {
        SQLManager taibangSqlManager = ManagerFactory.taibangSqlManager();

        //在t_bims_donor_register中查询该浆员当天是否挂号
        String sql = "select * from t_bims_donor_register as r left join t_bims_donor as d on r.donorId = d.donorId where (d.donorNo = ? or r.processNo = ?) and r.registerDate between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')";
        List<HashMap> resultList = taibangSqlManager.execute(new SQLReady(sql, new Object[] {donorNo,donorNo}), HashMap.class);

        if (resultList.size() > 0) {
            return true;
        } else {
            return false;
        }
    }



    /**
     * 发放餐券
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/view/publicMealTicket/{donorNo}")
    public AjaxResult publicMealTicket(@PathVariable String donorNo, HttpServletResponse response, HttpServletRequest request)
    {
        boolean isRegister = this.isRegister(donorNo);

        if (isRegister == true) {
            SQLManager jiangzhanSqlManager = ManagerFactory.jiangzhanSqlManager();
            String selectPublicMealTicketSql = "select * from plasma_meal_ticket as m where m.donorNo = ? and m.publicTime between DATE_FORMAT(CURRENT_DATE,'%Y%m%d0000000') and DATE_FORMAT(CURRENT_DATE,'%Y%m%d2300000')";
            List<HashMap> publicMealTicketList = jiangzhanSqlManager.execute(new SQLReady(selectPublicMealTicketSql, new Object[] {donorNo}), HashMap.class);
            if (publicMealTicketList.size()> 0) {
                HashMap publicMealTicket = publicMealTicketList.get(0);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssS");
                return AjaxResult.error("餐券已发放，发放时间：" + publicMealTicket.get("publictime"),"");
            } else {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssS");
                Date currentTime = new Date();
                String currentTimeStr = DateUtil.format(currentTime,"yyyyMMddHHmmssS").substring(0,15);
                HashMap params = new HashMap();
                params.put("donorNo",donorNo);
                params.put("publicTime",currentTimeStr);
                jiangzhanSqlManager.executeUpdate("INSERT INTO `plasma_meal_ticket`( `donorNo`, `publicTime`) VALUES (#donorNo#, #publicTime#)",params);
            }

            return AjaxResult.success("餐券发放成功");
        } else {
            return AjaxResult.error("该浆员未挂号");
        }
    }


    //下载导入模版
    @PostMapping("/donor/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<PlasmaDonor> util = new ExcelUtil<PlasmaDonor>(PlasmaDonor.class);
        util.importTemplateExcel(response, "用户数据");
    }

    @PreAuthorize("@ss.hasPermi('plasma:settlement')")
    @Log(title = "费用统计管理", businessType = BusinessType.EXPORT)
    @GetMapping("/settlement/create")
    public void settlementCreate(HttpServletRequest request, HttpServletResponse response,@RequestParam("dateRangeStart") String date1, @RequestParam("dateRangeEnd") String date2, @RequestParam(value = "name",required = false) String name , @RequestParam(value = "type",required = false) String type ) throws IOException {
        Date dateRangeStart = DateUtil.getDate(date1, "yyyy-MM-dd");
        Date dateRangeEnd = DateUtil.getDate(date2, "yyyy-MM-dd");

        File file = 车主路费统计直接走系统.start(dateRangeStart, dateRangeEnd, name, type);

        String sourceFolderPath = file.getPath();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        File sourceFolder = new File(sourceFolderPath);

        FileUtils.putFolderToZip(sourceFolder, sourceFolder.getName(), zip);

        IOUtils.closeQuietly(zip);

        System.out.println("Folder zipped successfully!");


        byte[] data = outputStream.toByteArray();
        if (response != null) {
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename='ruoyi.zip'");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }
    }

    //月度统计
    @PreAuthorize("@ss.hasPermi('plasma:statistics:month')")
    @Log(title = "费用统计管理", businessType = BusinessType.EXPORT)
    @GetMapping("/statistics/month/create")
    public void statisticsMonth(HttpServletRequest request, HttpServletResponse response,@RequestParam("dateRangeStart") String date1, @RequestParam("dateRangeEnd") String date2 ) throws IOException {
        Date dateRangeStart = DateUtil.getDate(date1, "yyyy-MM-dd");
        Date dateRangeEnd = DateUtil.getDate(date2, "yyyy-MM-dd");

        File yuangongFile = 每月员工统计.start(dateRangeStart, dateRangeEnd);
        File linkmanFile = 每月联络员统计.start(dateRangeStart, dateRangeEnd);


        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        FileUtils.putZip(zip, yuangongFile);
        FileUtils.putZip(zip, linkmanFile);

        IOUtils.closeQuietly(zip);
        System.out.println("Folder zipped successfully!");


        byte[] data = outputStream.toByteArray();
        if (response != null) {
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename='ruoyi.zip'");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }
    }
}
